package com.bear.newsset.adapter;

import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 为{@link BaseXRecyclerViewAdapter}使用的Holder
 */
public class BaseViewHolder extends RecyclerView.ViewHolder {
    /**
     * 就是单纯的去掉警告而已
     */
    public interface OnTouchListener {
        boolean onTouch(View v, MotionEvent event);
    }

    public BaseViewHolder(@NonNull View itemView) {
        super(itemView);
    }

    public void setOnClickListener(View.OnClickListener listener) {
        itemView.setOnClickListener( listener );
    }

    public void setOnLongClickListener(View.OnLongClickListener listener) {
        itemView.setOnLongClickListener( listener );
    }

    private long downTime = -1;
    /**
     * 优化版Touch
     * @param listener  监听器
     */
    public void setOnTouchListener(OnTouchListener listener) {
        itemView.setOnTouchListener((v, event) -> {
            switch ( event.getAction() ) {
                case MotionEvent.ACTION_DOWN:
                    downTime = System.currentTimeMillis();
                    break;
                case MotionEvent.ACTION_UP:
                    long upTime = System.currentTimeMillis();
                    //不是长按时才触发优化，防止长按后抬起时触发一次点击事件
                    if( upTime - downTime < ViewConfiguration.getLongPressTimeout() ) {
                        v.performClick();
                    }
                    downTime = -1;
                    break;
            }
            return listener.onTouch(v, event);
        });
    }

    /**
     * 原版Touch
     * @param listener  监听器
     */
    public void setOnTouchListener(View.OnTouchListener listener) {
        itemView.setOnTouchListener( listener );
    }
}
